package uvt.gui.mainframe.subpanel.addvehicle;

import javax.swing.JButton;
import javax.swing.JComboBox;

import uvt.database.Database;
import uvt.database.InsertOperations;
import uvt.gui.mainframe.object.InfoFrame;
import uvt.gui.mainframe.object.command.Command;
import uvt.gui.mainframe.object.memento.ButtonOperations;
import uvt.gui.mainframe.object.memento.MementoImp;
import uvt.gui.mainframe.object.memento.UndoOperationButton;
import uvt.gui.mainframe.object.memento.container.ButtonOperationBackup;
import uvt.gui.mainframe.object.memento.container.Container;
import uvt.gui.mainframe.object.observer.ConcreteObservable;
import uvt.gui.mainframe.subpanel.addroute.RouteNameTextField;
import uvt.map.graph.element.Vehicle;
import uvt.map.graph.element.VehicleColor;

public class AddVehicleButton extends JButton implements Command {
	
	private VehicleNameTextField txtVehicleName;
	private RouteNameTextField txtRouteName;
	private JComboBox<String> vehicleType;
	private UndoOperationButton undo;
	private MementoImp memento;
	
	public AddVehicleButton(VehicleNameTextField txtVehicleName,RouteNameTextField txtRouteName,
			                JComboBox<String> type,UndoOperationButton undo,MementoImp memento) {
		super("Add Vehicle");
		this.txtVehicleName = txtVehicleName;
		this.vehicleType = type;	
		this.memento = memento;
		this.undo = undo;
		this.txtRouteName = txtRouteName;
	}
	
	public void execute() {
		try {
			validateTextFields();
			final Vehicle vehicle = new Vehicle();
			vehicle.setName(txtVehicleName.getText());
			vehicle.setType(vehicleType.getSelectedItem().toString());
			vehicle.setColor(VehicleColor.getColorForVehicle(vehicleType.getSelectedItem().toString()));
			vehicle.setRoute(txtRouteName.getText());
			((InsertOperations)Database.getInstace()).insertRowVehicle(vehicle);
			ConcreteObservable.getVehiclePanelObservableInstance().stateChanged();
			memento.setContainer(new Container(txtVehicleName.getText()));
			ButtonOperationBackup.getInstance().addReference(ButtonOperations.ADDVEHICLE,memento.backup());
			undo.setEnabled(true);
			Thread t = new Thread(new Runnable() {
				public void run() {
					new InfoFrame("Information","Vehicle " + vehicle.getName() + " was added in database!");
				}
			});
			t.start();
		} catch(final Exception ex) {
			Thread t = new Thread(new Runnable() {
				public void run() {
					new InfoFrame("Error",ex.getMessage());
				}
			});
			t.start();
		}
	}
	
	public void validateTextFields() throws Exception {
		if(txtVehicleName.getText().equals("")) throw new Exception("Vehicle name field empty!");		
	}

}
